#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"

void StackInit(Stack* p)
{
	assert(p);

	Stack* tmp = (Stack*)malloc(sizeof(Stack));
	if (tmp == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	else
	{
		p->a = NULL;
		p->capacity = 0;
		p->size = 0;
	}
}

bool StackEmpty(Stack* p)
{
	assert(p);
	return p->size == 0;
}


void StackPush(Stack* p, SDataType x)
{
	assert(p);

	if (p->capacity == p->size)
	{
		int NewCapacity = p->capacity == 0 ? 4 : p->capacity * 2;
		SDataType* tmp = (SDataType*)realloc(p->a, sizeof(SDataType) * NewCapacity);
		if (tmp == NULL)
		{
			perror("realloc");
			exit(-1);
		}

		p->a = tmp;
		p->capacity = NewCapacity;
	}

	p->a[p->size] = x;
	p->size++;
}

void StackPop(Stack* p)
{
	assert(p);
	assert(!StackEmpty(p));

	p->size--;
}
SDataType StackTop(Stack* p)
{
	assert(p);
	assert(!StackEmpty(p));

	return p->a[p->size - 1];
}
int StackSize(Stack* p)
{
	assert(p);
	
	return p->size;
}
void StackDestroy(Stack* p)
{
	assert(p);

	free(p->a);
	p->a = NULL;
	p->size = 0;
	p->capacity = 0;
}